package com.lottery.im.module.contact.ui;

import android.os.Handler;
import android.os.Looper;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import butterknife.BindView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.flyco.tablayout.widget.MsgView;
import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.lottery.im.R;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.module.chat.ui.UserProfileFragment;
import com.lottery.im.module.contact.adapter.ContactAdapter;
import com.lottery.im.module.contact.presenter.ContactPresenter;
import com.lottery.im.module.contact.view.ContactView;
import com.lottery.im.module.tim.model.ContactFriend;
import com.lottery.im.module.tim.model.ContactGroup;
import com.lottery.im.module.tim.model.FriendProfile;
import com.lottery.im.module.tim.model.FriendshipInfo;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 主页联系人
 */
public class ContactFragment extends BaseSwipeFragment<ContactPresenter>
    implements ContactView {

  @BindView(R.id.list) RecyclerView mList;

  private int mFriendUnreadNum = 0, mGroupUnreadNum = 0;

  private List<MultiItemEntity> mItemEntities;
  private ContactAdapter mAdapter;

  private MsgView mTvUnreadNum;
  private View mHeaderView;

  @Override protected int getLayoutResId() {
    return R.layout.fragment_contact;
  }

  @Override protected void initPresenter() {
    presenter = new ContactPresenter(getActivity(), this, this);
    presenter.init();
  }

  @Override public void initView() {

    mList.setLayoutManager(new LinearLayoutManager(getActivity()));

    RecyclerViewDivider.with(mActivity)
        .color(ContextCompat.getColor(mActivity, R.color.windowBackground))
        .size((int) mActivity.getResources().getDimension(R.dimen.line_size))
        .hideLastDivider()
        .build()
        .addTo(mList);

    mItemEntities = new ArrayList<>();
    mAdapter = new ContactAdapter(mItemEntities);
    mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
      @Override public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        ContactFriend contactFriend = (ContactFriend) mItemEntities.get(position);
        startFragment(UserProfileFragment.create(contactFriend.friendProfile.getIdentify()));
      }
    });
    mList.setAdapter(mAdapter);
    mAdapter.addHeaderView(getHeaderView());
    refreshData();
    presenter.initManagerPresenter();
  }

  /*
   * 添加头部 验证通知 + 我的群聊
   * */
  private View getHeaderView() {
    if (null == mHeaderView) {
      mHeaderView = getLayoutInflater().inflate(R.layout.header_friend_group, null);
      mTvUnreadNum = mHeaderView.findViewById(R.id.tv_unread_num);
      mHeaderView.findViewById(R.id.layout_friend).setOnClickListener(
          v -> startFragment(new ShipManageMessageFragment()));
      mHeaderView.findViewById(R.id.layout_black_list)
          .setOnClickListener(v -> startFragment(new BlackListFragment()));
      mHeaderView.findViewById(R.id.layout_group).setOnClickListener(
          v -> startFragment(new GroupListFragment()));
    }
    return mHeaderView;
  }

  /*
   * 未读验证通知数量 = 好友验证 + 群组验证
   * */
  private void setUnreadNum() {
    if (mFriendUnreadNum + mGroupUnreadNum > 0) {
      mTvUnreadNum.setText(String.valueOf(mFriendUnreadNum + mGroupUnreadNum));
      mTvUnreadNum.setVisibility(View.VISIBLE);
    } else {
      mTvUnreadNum.setVisibility(View.GONE);
    }
  }

  /*
   *  获取好友分组数据
   * */
  private void refreshData() {

    Map<String, List<FriendProfile>> friends = FriendshipInfo.getInstance().getFriends();
    List<String> groupNames = FriendshipInfo.getInstance().getGroups();
    mItemEntities.clear();

    for (String groupName : groupNames) {
      ContactGroup contactGroup;
      if (groupName.equals("")) {
        contactGroup = new ContactGroup("我的好友", friends.get(groupName).size());
        mItemEntities.add(contactGroup);
      } else {
        contactGroup = new ContactGroup(groupName, friends.get(groupName).size());
        mItemEntities.add(contactGroup);
      }
      for (FriendProfile friendProfile : friends.get(groupName)) {
        ContactFriend contactFriend = new ContactFriend(friendProfile);
        contactGroup.addSubItem(contactFriend);
      }
    }
    mAdapter.notifyDataSetChanged();
    if (mAdapter.isExpand()) {
      mAdapter.expandAll();
    }
  }

  /*
   * 数据出现变动、刷新列表
   * */
  @Override public void refreshFriendList() {
    // 删除好友的时候，直接读取的话 会比删除数据库快，所以做一个延迟
    new Handler(Looper.getMainLooper()).postDelayed(() -> refreshData(), 1000);
  }

  @Override public void setFriendshipUnread(int unreadCount) {
    mFriendUnreadNum = unreadCount;
    setUnreadNum();
  }

  @Override public void setGroupUnread(int unreadCount) {
    mGroupUnreadNum = unreadCount;
    setUnreadNum();
  }

  @Override protected boolean canDragBack() {
    return false;
  }

  @Override public void onDestroy() {
    super.onDestroy();
    presenter.stop();
  }
}
